import { Context } from 'koa';
import KoaRouter from 'koa-router';
import Card from '@/models/card';
import CardList from '@/models/cardList';
import { validate } from '@/middleware/validate';
import Joi from 'joi';
import { v4 as uuidv4 } from 'uuid';
import { CreateCardRequest, UpdateCardRequest } from '@/types/route';
export default (router: KoaRouter) => {
    // 获取卡片
    router.get('/card/:cardId', async (ctx: Context) => {
        const { cardId } = ctx.params;
        const card = await Card.findOne({ cardId });
        ctx.setResponse(card, '获取卡片成功');
    });

    // 修改卡片
    router.put('/card/:cardId',
        validate(Joi.object({
            title: Joi.string().messages({
                'string.empty': '标题不能为空'
            }),
            content: Joi.string().messages({
                'string.empty': '内容不能为空'
            }),
            listId: Joi.string(),
            order: Joi.number().integer().min(0).messages({
                'number.base': '顺序必须是数字',
                'number.integer': '顺序必须是整数',
                'number.min': '顺序不能小于0'
            })
        })),
        async (ctx: Context) => {
            try {
                const { cardId } = ctx.params;
                const { title, content, listId, order } = ctx.request.body as UpdateCardRequest;
                // 查找目标卡片
                const targetCard = await Card.findOne({ cardId });
                if (!targetCard) {
                    ctx.status = 404;
                    return ctx.setResponse(null, '卡片不存在', 404);
                }

                const updateData: { title?: string; content?: string; listId?: string; order?: number; updatedAt: number } = {
                    updatedAt: Date.now()
                };
                if (title) updateData.title = title;
                if (content) updateData.content = content;

                // 如果需要更改列表，验证目标列表是否存在
                if (listId) {
                    const targetList = await CardList.findOne({ listId });
                    if (!targetList) {
                        ctx.status = 404;
                        return ctx.setResponse(null, '目标列表不存在', 404);
                    }
                    updateData.listId = listId;
                }

                const session = await Card.startSession();
                session.startTransaction();
                try {
                    if(listId && order !== undefined){
                        const targetListId = listId || targetCard.listId;
                        const allCards = await Card.find({ listId: targetListId }).session(session);
                        const newOrder = Math.min(order, allCards.length);
                        // 添加 order 到更新数据
                        updateData.order = newOrder;
                        // 原列表处理（跨列表移动时）
                        if (listId && listId !== targetCard.listId) {
                            await Card.updateMany(
                                { listId: targetCard.listId, order: { $gt: targetCard.order } },
                                { $inc: { order: -1 } },
                                { session }
                            );
                        }// 目标列表处理
                        if (targetListId !== targetCard.listId) {
                            await Card.updateMany(
                                { listId: targetListId, order: { $gte: newOrder } },
                                { $inc: { order: 1 } },
                                { session }
                            );
                        } else {
                            if (newOrder < targetCard.order) {
                                await Card.updateMany(
                                    { listId: targetListId, order: { $gte: newOrder, $lt: targetCard.order } },
                                    { $inc: { order: 1 } },
                                    { session }
                                );
                            } else if (newOrder > targetCard.order) {
                                await Card.updateMany(
                                    { listId: targetListId, order: { $gt: targetCard.order, $lte: newOrder } },
                                    { $inc: { order: -1 } },
                                    { session }
                                );
                            }
                        }
                    }
                    // 更新当前卡片（带事务和版本检查）
                    const updatedCard = await Card.findOneAndUpdate(
                        { cardId, version: targetCard.version },
                        { ...updateData, $inc: { version: 1 } }, 
                        { new: true, session }
                    );
                
                    if (!updatedCard) {
                        await session.abortTransaction();
                        ctx.status = 409;
                        return ctx.setResponse(null, '数据已被其他用户修改，请刷新后重试', 409);
                    }
                
                    await session.commitTransaction();
                    ctx.setResponse(updatedCard, '修改卡片成功');
                } catch(e){
                    console.log(e);
                    await session.abortTransaction();
                    ctx.status = 500;
                    ctx.setResponse(null, '修改卡片失败', 500);
                } finally {
                    session.endSession();
                }
            } catch {
                ctx.status = 500;
                ctx.setResponse(null, '修改卡片失败', 500);
            }
        }
    );

    // 创建卡片
    router.post('/card',
        validate(Joi.object({
            title: Joi.string().required().messages({
                'string.empty': '标题不能为空',
                'any.required': '标题是必填项'
            }),
            listId: Joi.string().required().messages({
                'string.empty': '列表ID不能为空',
                'any.required': '列表ID是必填项'
            })
        })),
        async (ctx: Context) => {
            try {
                const { title, listId } = ctx.request.body as CreateCardRequest;

                // 验证目标列表是否存在
                const targetList = await CardList.findOne({ listId });
                if (!targetList) {
                    ctx.status = 404;
                    return ctx.setResponse(null, '目标列表不存在', 404);
                }
                // 获取当前列表中最大的order
                const maxOrderCard = await Card.findOne({ listId }).sort({ order: -1 });
                const order = maxOrderCard ? maxOrderCard.order + 1 : 0;
                // 创建新卡片
                const newCard = await Card.create({
                    cardId: uuidv4(),
                    title,
                    listId,
                    order
                });
                ctx.setResponse(newCard, '创建卡片成功');
            } catch(e) {
                console.log(e);
                ctx.status = 500;
                ctx.setResponse(null, '创建卡片失败', 500);
            }
        }
    );

    // 删除卡片
    router.delete('/card/:cardId', async (ctx: Context) => {
        const session = await Card.startSession();
        session.startTransaction();
        
        try {
            const { cardId } = ctx.params;
            const targetCard = await Card.findOne({ cardId }).session(session);
            
            if (!targetCard) {
                await session.abortTransaction();
                ctx.status = 404;
                return ctx.setResponse(null, '卡片不存在', 404);
            }

            const deleteResult = await Card.deleteOne({ 
                cardId, 
                version: targetCard.version 
            }).session(session);

            if (deleteResult.deletedCount === 0) {
                await session.abortTransaction();
                ctx.status = 409;
                return ctx.setResponse(null, '数据已被其他用户修改，请刷新后重试', 409);
            }

            await Card.updateMany(
                { 
                    listId: targetCard.listId,
                    order: { $gt: targetCard.order }
                },
                { $inc: { order: -1 } },
                { session }
            );

            await session.commitTransaction();
            ctx.setResponse(null, '删除卡片成功');
        } catch (error) {
            await session.abortTransaction();
            ctx.status = 500;
            ctx.setResponse(null, '删除卡片失败', 500);
        } finally {
            session.endSession();
        }
    });
}
